package com.zangchat.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.common.core.domain.AjaxResult;
import com.zangchat.domain.ChatUsers;
import com.zangchat.service.IChatUsersService;
import com.zangchat.service.IPageInfoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.zangchat.mapper.ChatConcernusersMapper;
import com.zangchat.domain.ChatConcernusers;
import com.zangchat.service.IChatConcernusersService;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 用户关注 服务层实现
 *
 * @author wudi
 * @date 2020-07-15
 */
@Service
public class ChatConcernusersServiceImpl extends ServiceImpl<ChatConcernusersMapper, ChatConcernusers> implements IChatConcernusersService
{

    @Autowired
    private IChatUsersService chatUsersService;
    @Autowired
    private IPageInfoService pageInfoService;
    /**
     * 关注数量
     * @param userId
     * @return
     */
    public int concernCount(Long userId){
        ChatConcernusers chatConcernusers=new ChatConcernusers();
        chatConcernusers.setUserId(userId);
        QueryWrapper<ChatConcernusers> queryWrapper=new QueryWrapper<>(chatConcernusers);
        queryWrapper.eq("status","1").or().eq("status","2");
        return baseMapper.selectCount(queryWrapper);
    }
    /**
     * 粉丝数量
     * @param userId
     * @return
     */
    public int fansCount(Long userId){
        ChatConcernusers chatConcernusers=new ChatConcernusers();
        chatConcernusers.setToUserId(userId);
        QueryWrapper<ChatConcernusers> queryWrapper=new QueryWrapper<>(chatConcernusers);
        queryWrapper.eq("status","1").or().eq("status","2");
        return baseMapper.selectCount(queryWrapper);
    }
    /**
     * 关注列表
     * @param userId
     * @return
     */
    @Override
    public AjaxResult selectChatConcernusersByUserId(Long userId, Integer pageNum,Integer pageSize) {
        AjaxResult ajaxResultUser = chatUsersService.checkedUser(userId);
        if (Integer.parseInt(ajaxResultUser.get("code")+"")!=1){
            return ajaxResultUser;
        }

        pageInfoService.initPagePageHelper(pageNum,pageSize);
        List<Map<String, Object>> list = baseMapper.selectChatConcernusersByUserId(userId);
        Map<String, Object> map = pageInfoService.initPageInfo(list);
        return AjaxResult.success(map);
    }

    /**
     * 关注
     * @param userId 关注用户id
     * @param toUserId 被关注用户id
     * @return
     */
    @Override
    @Transactional
    public AjaxResult doConcern(Long userId, Long toUserId) {
        try{
            AjaxResult ajaxResultUser = chatUsersService.checkedUser(userId);
            if (Integer.parseInt(ajaxResultUser.get("code")+"")!=1){
                return ajaxResultUser;
            }
            AjaxResult ajaxResultToUser = chatUsersService.checkedUser(toUserId);
            if (Integer.parseInt(ajaxResultToUser.get("code")+"")!=1){
                return ajaxResultToUser;
            }
            //是否已被关注 如果已被关注则状态改为互关
            ChatConcernusers chatConcernusers=new ChatConcernusers();
            chatConcernusers.setUserId(toUserId);
            chatConcernusers.setToUserId(userId);
            QueryWrapper<ChatConcernusers> queryWrapper=new QueryWrapper<>(chatConcernusers);
            ChatConcernusers chatConcernusers1 = baseMapper.selectOne(queryWrapper);
            ChatConcernusers newChatConcernusers=new ChatConcernusers();
            newChatConcernusers.setUserId(userId);
            newChatConcernusers.setToUserId(toUserId);
            newChatConcernusers.setCreateTime(new Date());
            if (chatConcernusers1!=null){
                chatConcernusers1.setStatus(2);
//                UpdateWrapper<ChatConcernusers> updateWrapper=new UpdateWrapper<>(chatConcernusers1);
                int i = baseMapper.updateById(chatConcernusers1);
                if (i<1){
                    TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                    return AjaxResult.error();
                }
                newChatConcernusers.setStatus(2);
            }else {
                newChatConcernusers.setStatus(1);
            }
            int j = baseMapper.insert(newChatConcernusers);
            if (j<1){
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                return AjaxResult.error();
            }
            //关注数+1
            ChatUsers fromUhatUsers = chatUsersService.getBaseMapper().selectById(userId);
            fromUhatUsers.setConcernNum(fromUhatUsers.getConcernNum()+1);
            chatUsersService.getBaseMapper().updateById(fromUhatUsers);
            //被关注人粉丝数量+1
            ChatUsers toUhatUsers = chatUsersService.getBaseMapper().selectById(toUserId);
            toUhatUsers.setConcernedNum(toUhatUsers.getConcernedNum()+1);
            chatUsersService.getBaseMapper().updateById(toUhatUsers);
            return AjaxResult.success();
        }catch (Exception e){
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return AjaxResult.error();
        }

    }
    /**
     * 取消关注
     * @param userId 关注用户id
     * @param toUserId 被关注用户id

     * @return
     */
    @Override
    public AjaxResult restConcern(Long userId, Long toUserId) {
        try{
            AjaxResult ajaxResultUser = chatUsersService.checkedUser(userId);
            if (Integer.parseInt(ajaxResultUser.get("code")+"")!=1){
                return ajaxResultUser;
            }
            AjaxResult ajaxResultToUser = chatUsersService.checkedUser(toUserId);
            if (Integer.parseInt(ajaxResultToUser.get("code")+"")!=1){
                return ajaxResultToUser;
            }
            //是否已互关 如果已被关注则状态改为单方面关注
            ChatConcernusers chatConcernusers=new ChatConcernusers();
            chatConcernusers.setUserId(toUserId);
            chatConcernusers.setToUserId(userId);
            QueryWrapper<ChatConcernusers> queryWrapper=new QueryWrapper<>(chatConcernusers);
            ChatConcernusers chatConcernusers1 = baseMapper.selectOne(queryWrapper);
            ChatConcernusers newChatConcernusers=new ChatConcernusers();
            newChatConcernusers.setUserId(userId);
            newChatConcernusers.setToUserId(toUserId);
            if (chatConcernusers1!=null){
                if (chatConcernusers1.getStatus()==2){
                    chatConcernusers1.setStatus(1);
                    int i = baseMapper.updateById(chatConcernusers1);
                    if (i<1){
                        TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                        return AjaxResult.error();
                    }
                }
            }
            QueryWrapper<ChatConcernusers> deleteWrapper=new QueryWrapper<>(newChatConcernusers);
            int j =  baseMapper.delete(deleteWrapper);
            if (j<1){
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                return AjaxResult.error();
            }
            //关注数-1
            ChatUsers chatUsers = chatUsersService.getBaseMapper().selectById(userId);
            chatUsers.setConcernNum(chatUsers.getConcernNum()-1);
            chatUsersService.getBaseMapper().updateById(chatUsers);
            //被关注数-1
            ChatUsers toChatUsers = chatUsersService.getBaseMapper().selectById(toUserId);
            toChatUsers.setConcernedNum(toChatUsers.getConcernedNum()-1);
            chatUsersService.getBaseMapper().updateById(toChatUsers);
            return AjaxResult.success();
        }catch (Exception e){
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return AjaxResult.error();
        }

    }
    /**
     * 拉黑
     * @param userId 用户id
     * @param toUserId 被拉黑用户id

     * @return
     */
    @Override
    @Transactional
    public AjaxResult changeBlack(Long userId, Long toUserId) {

        AjaxResult ajaxResultUser = chatUsersService.checkedUser(userId);
        if (Integer.parseInt(ajaxResultUser.get("code")+"")!=1){
            return ajaxResultUser;
        }
        AjaxResult ajaxResultToUser = chatUsersService.checkedUser(toUserId);
        if (Integer.parseInt(ajaxResultToUser.get("code")+"")!=1){
            return ajaxResultToUser;
        }
        //主动拉黑的人
        ChatConcernusers fromUsers=new ChatConcernusers();
        fromUsers.setUserId(userId);
        fromUsers.setToUserId(toUserId);
        QueryWrapper<ChatConcernusers> fromQueryWrapper=new QueryWrapper<>(fromUsers);
        ChatConcernusers fromUsers1 = baseMapper.selectOne(fromQueryWrapper);
        if (fromUsers1==null){

            fromUsers.setStatus(-1);
            fromUsers.setCreateTime(new Date());
            baseMapper.insert(fromUsers);
        }else {
            fromUsers1.setStatus(-1);
            baseMapper.updateById(fromUsers1);
            //关注-1
            ChatUsers chatUsers = chatUsersService.getBaseMapper().selectById(userId);
            chatUsers.setConcernNum(chatUsers.getConcernNum()-1);
            chatUsersService.getBaseMapper().updateById(chatUsers);
        }
        //被动拉黑的人
        ChatConcernusers toUsers=new ChatConcernusers();
        toUsers.setUserId(toUserId);
        toUsers.setToUserId(userId);
        QueryWrapper<ChatConcernusers> toQueryWrapper=new QueryWrapper<>(toUsers);
        ChatConcernusers toUsers1 = baseMapper.selectOne(toQueryWrapper);
//        if (toUsers1==null){
//            toUsers.setStatus(-1);
//            toUsers.setCreateTime(new Date());
//            baseMapper.insert(toUsers);
//        }
        if(toUsers1!=null) {
//            toUsers1.setStatus(-1);
//            baseMapper.updateById(toUsers1);
            //粉丝数-1
            ChatUsers toChatUsers = chatUsersService.getBaseMapper().selectById(toUserId);
            toChatUsers.setConcernedNum(toChatUsers.getConcernedNum()-1);
            chatUsersService.getBaseMapper().updateById(toChatUsers);
        }
        return AjaxResult.success();
    }
    /**
     * 粉丝列表
     * @param userId 关注用户id
     * @param
     * @return
     */
    @Override
    public AjaxResult selectFansListByToUserId(Long userId, Integer pageNum, Integer pageSize) {
        AjaxResult ajaxResultUser = chatUsersService.checkedUser(userId);
        if (Integer.parseInt(ajaxResultUser.get("code")+"")!=1){
            return ajaxResultUser;
        }

        pageInfoService.initPagePageHelper(pageNum,pageSize);
        List<Map<String, Object>> list = baseMapper.selectFansListByUserId(userId);
        Map<String, Object> map = pageInfoService.initPageInfo(list);
        return AjaxResult.success(map);

    }
    /**
     * 黑名单列表
     * @param userId 关注用户id
     * @param
     * @return
     */
    @Override
    public AjaxResult selectBlackListByUserId(Long userId, Integer pageNum, Integer pageSize) {
        AjaxResult ajaxResultUser = chatUsersService.checkedUser(userId);
        if (Integer.parseInt(ajaxResultUser.get("code")+"")!=1){
            return ajaxResultUser;
        }

        pageInfoService.initPagePageHelper(pageNum,pageSize);
        List<Map<String, Object>> list = baseMapper.selectBlackListByUserId(userId);
        Map<String, Object> map = pageInfoService.initPageInfo(list);
        return AjaxResult.success(map);
    }
    /**
     * 取消拉黑
     * @param userId 关注用户id
     * @param
     * @return
     */
    @Override
    public AjaxResult restChangeBlack(Long userId, Long toUserId) {
        AjaxResult ajaxResultUser = chatUsersService.checkedUser(userId);
        if (Integer.parseInt(ajaxResultUser.get("code")+"")!=1){
            return ajaxResultUser;
        }
        AjaxResult ajaxResultToUser = chatUsersService.checkedUser(toUserId);
        if (Integer.parseInt(ajaxResultToUser.get("code")+"")!=1){
            return ajaxResultToUser;
        }
        //被取消人是否关注了操作用户
        ChatConcernusers toUsers=new ChatConcernusers();
        toUsers.setUserId(toUserId);
        toUsers.setToUserId(userId);
        QueryWrapper<ChatConcernusers> toQueryWrapper=new QueryWrapper<>(toUsers);
        ChatConcernusers toUsers1 = baseMapper.selectOne(toQueryWrapper);
        if(toUsers1!=null && toUsers1.getStatus()!=-1) {
            //粉丝数+1
            ChatUsers toChatUsers = chatUsersService.getBaseMapper().selectById(toUserId);
            toChatUsers.setConcernedNum(toChatUsers.getConcernedNum()+1);
            chatUsersService.getBaseMapper().updateById(toChatUsers);
        }
        ChatConcernusers Blackusers=new ChatConcernusers();
        Blackusers.setUserId(userId);
        Blackusers.setToUserId(toUserId);
        int i = baseMapper.delete(new QueryWrapper<ChatConcernusers>(Blackusers));
        return i>=1?AjaxResult.success():AjaxResult.error();
    }


}